<!-- 角色列表 -->
<template>
  <div class="rolelist">
    <el-col :span="24">
      <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 20px;">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
    <el-card class="box-card">
      <div class="text item" style="line-height: 0;text-align: left;">
        <el-button type="primary" style="margin-bottom: 20px;" @click="btnStatus.isShow = true">新增角色</el-button>
        <el-table :data="tableData" style="width: 100%" border>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row v-for="(item, index) in scope.row.children" style="border-bottom: 1px lightslategray solid;"
                class="wyt-row">
                <el-col :span="4">
                  <el-tag type="primary" @click="handleClick(item, scope.row.id)">{{ item.authName }}<p
                      class="iconfont el-icon-close" @click="delTag(index, scope.row.id)"></p>
                  </el-tag>
                </el-col>
                <el-col :span="20">
                  <el-row v-for="(item2, index2) in item.children">
                    <el-col :span="8">
                      <el-tag type="success" @click="handleClick(item2, scope.row.id)">{{ item2.authName }}
                        <p class="iconfont el-icon-close" @click="delTag(index2, scope.row.id)"></p>
                      </el-tag>
                    </el-col>
                    <el-col :span="16">
                      <el-tag type="info" v-for="(item3, index3) in item2.children"
                        @click="handleClick(item3, scope.row.id)">{{ item3.authName }}
                        <p class="iconfont el-icon-close" @click="delTag(index3, scope.row.id)"></p>
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="">
            <!-- 箭头 -->
            <template slot-scope="scope">
              <el-icon>
                <arrow-right />
              </el-icon>
            </template>
          </el-table-column>
          <el-table-column label="" prop="id">
          </el-table-column>
          <el-table-column label="角色名称" prop="roleName">
          </el-table-column>
          <el-table-column label="描述" prop="roleDesc">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" @click="editRole(scope.row.id)">编辑</el-button>
              <el-button type="danger" @click="delRole(scope.row.id)">删除</el-button>
              <el-button type="info" @click="setRole(scope.row.id, scope.row.children)">设置</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 新增角色弹窗 -->
    <el-dialog title="添加角色" :visible.sync="btnStatus.isShow" width="30%" center style="line-height: 0;">
      <el-form ref="formRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input autocomplete="off" v-model="formAddData.roleName" />
          <span style="display: block; height: 20px;color: red;">{{ formAddData.roleNameMsg }}</span>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input autocomplete="off" v-model="formAddData.roleDesc" />
          <span style="display: block; height: 20px;color: red;">{{ formAddData.roleDescMsg }} </span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="btnStatus.isShow = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色弹出框 -->
    <el-dialog title="编辑角色" :visible.sync="btnStatus.isEdit" width="30%" center style="line-height: 0;">
      <el-form ref="formRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input autocomplete="off" v-model="formEditData.roleName" placeholder="原角色名称" />
          <span style="display: block; height: 20px;color: red;">{{ formEditData.roleNameMsg }}</span>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input autocomplete="off" v-model="formEditData.roleDesc" placeholder="原角色描述" />
          <span style="display: block; height: 20px;color: red;">{{ formEditData.roleDescMsg }} </span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="btnStatus.isEdit = false">取 消</el-button>
        <el-button type="primary" @click="updateRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限弹出框 -->
    <el-dialog title="分配权限" :visible.sync="formSetRoleData.isSet" width="30%" center style="line-height: 0;">
      <el-tree ref="tree" :data="roleList" :default-checked-keys="rolearr" show-checkbox node-key="id" highlight-current
        :props="{
          children: 'children',
          label: 'authName'
        }">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="formSetRoleData.isSet = false">取 消</el-button>
        <el-button type="primary" @click="assignRolePermissions">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>
<style scoped>
.wyt-row .el-tag {
  margin: 5px;
}
</style>
<script>
import axios from 'axios'
import http from '@/mixins/http.js'
export default {
  mixins: [http()],
  data() {
    return {
      baseURL: 'http://43.138.15.137:7000/api/private/v1',
      token: localStorage.getItem('token'),
      tableData: [],
      // 角色列表
      roleList: [],
      // 数据回填的id数组
      rolearr: [],
      // 按钮状态数组
      btnStatus: {
        isShow: false,
        isEdit: false,
        isDel: false,
        isSet: false
      },
      // 添加角色
      formAddData: {
        roleName: '',
        roleDesc: '',
        // 提示
        roleNameMsg: '',
        roleDescMsg: ''
      },
      // 编辑角色
      formEditData: {
        roleid: '',
        roleName: '',
        roleDesc: '',
        // 提示
        roleNameMsg: '',
        roleDescMsg: ''
      },
      // 删除角色对象数组
      formDelRoleData: {
        roleid: 0,
      },
      // 分配权限
      formSetRoleData: {
        roleid: 0,
        authId: [],
        isSet: false
      },
      // 删除角色指定权限
      formDelRoleAuthData: {
        roleid: 0,
        authId: 0
      },

    }
  },
  created() {
    this.getRoleList()
    this.getRightsTree()
  },
  methods: {
    // 获取权限树数据
    getRightsTree() {
      axios.get(`${this.baseURL}/rights/tree`, {
        headers: {
          'Authorization': this.token
        }
      }).then(res => {
        this.roleList = res.data.data
      })
    },
    async getRoleList() {
    },
    methods: {
      async getRoleList() {
        try {
          const res = await this.$httpGet('/roles')
          this.tableData = res.data.data
          return res.data.data
        } catch (error) {
          console.error('请求失败:', error)
          this.$message.error('数据加载失败')
          return null
        }

      },
      async addRole() {

        this.btnStatus.isShow = false
        // 校验
        if (this.formAddData.roleName == '') {
          this.formAddData.roleNameMsg = '请输入角色名称'
          return
        }
        if (this.formAddData.roleDesc == '') {
          this.formAddData.roleDescMsg = '请输入角色描述'
          return
        }
        try {
          const res = await this.$httpPost('/roles', {
            roleName: this.formAddData.roleName,
            roleDesc: this.formAddData.roleDesc
          })
          this.getRoleList()
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.formAddData.roleName = ''
          this.formAddData.roleDesc = ''
        } catch (error) {
          console.error('请求失败:', error)
          this.$message.error('数据加载失败')
          return null
        }

      },
      editRole(id) {
        this.btnStatus.isEdit = true
        this.formEditData.roleid = id
        // 校验
      },
      async updateRole() {
        // 校验
        if (this.formEditData.roleName == '') {
          this.formEditData.roleNameMsg = '请输入角色名称'
          return
        }
        if (this.formEditData.roleDesc == '') {
          this.formEditData.roleDescMsg = '请输入角色描述'
          return
        }
        try {
          const tempArray = {
            roleName: this.formEditData.roleName,
            roleDesc: this.formEditData.roleDesc
          }
          const res = await this.$httpPut('/roles/' + this.formEditData.roleid, tempArray)
          this.getRoleList()
          this.$message({
            message: '编辑成功',
            type: 'success'
          })
          this.btnStatus.isEdit = false
          this.formEditData.roleName = ''
          this.formEditData.roleDesc = ''
        } catch (error) {
          console.error('请求失败:', error)
          this.$message.error('数据加载失败')
          return null
        }

      },
      delRole(id) {
        this.formDelRoleData.roleid = id
        this.$confirm('确定删除该角色吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(async () => {
          try {
            await this.$httpDelete('/roles/' + this.formDelRoleData.roleid)
            this.getRoleList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } catch (error) {
            console.error('请求失败:', error)
            this.$message.error('数据加载失败')
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      setRole(id, obj) {
        this.formSetRoleData.isSet = true
        this.formSetRoleData.roleid = id
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedKeys([])
          this.rolearr = []
        }
        this.collectPermissionIds(obj)
      },
      collectPermissionIds(items) {
        items.forEach(item => {
          if (item.children?.length) {
            this.collectPermissionIds(item.children)
          } else {
            this.rolearr.push(item.id)
          }
        })
      },
      async assignRolePermissions() {
        try {
          const authIds = this.$refs.tree.getCheckedKeys()
          await this.$httpPost(`/roles/${this.formSetRoleData.roleid}/rights`, {
            rids: authIds.join(',')
          })
          this.$message.success('权限分配成功')
          this.getRoleList()
          this.formSetRoleData.isSet = false
        } catch (error) {
          this.$message.error('权限分配失败')
        }
      },
      // 对话框管理
      openRoleDialog(type, id) {
        this.updateDialogState(type, true)
        if (id) this.formEditData.roleid = id
      },
      handleClick(item, roleid) {
        this.formDelRoleAuthData.roleid = roleid
        this.formDelRoleAuthData.authId = item.id
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(async () => {
          try {
            const res = await this.$httpDelete(`/roles/${this.formDelRoleAuthData.roleid}/rights/${this.formDelRoleAuthData.authId}`)
            let { data, meta } = res.data
            if (meta.status == 200) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.getRoleList()
            }
          } catch (error) {
            console.error('请求失败:', error)
            this.$message.error('数据加载失败')
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    }
  }
</script>